import os
from dotenv import load_dotenv, find_dotenv
_ = load_dotenv(find_dotenv())

# from langchain_openai import ChatOpenAI, OpenAIEmbeddings
# llm = ChatOpenAI(temperature=0, model="gpt-4o")
# embeddings = OpenAIEmbeddings()

from langchain_community.chat_models import ChatZhipuAI 
from langchain_community.embeddings import ZhipuAIEmbeddings
llm = ChatZhipuAI(model="glm-4-plus",
                  temperature=0.9,              
                )
embeddings = ZhipuAIEmbeddings(model="Embedding-3")

from langchain.chains import RetrievalQA
from langchain_chroma import Chroma
from langchain_text_splitters import CharacterTextSplitter
from langchain_community.document_loaders import TextLoader

doc_path = "./data/" + "大语言模型提示技巧.txt" 
loader = TextLoader(doc_path, "utf-8")
documents = loader.load()
text_splitter = CharacterTextSplitter(
    chunk_size=1000, 
    chunk_overlap=0
)
texts = text_splitter.split_documents(documents)
docsearch = Chroma.from_documents(
    texts, 
    embeddings, 
    collection_name="prompt-skills"
)
doc_ret = RetrievalQA.from_chain_type(
    llm=llm, 
    chain_type="stuff", 
    retriever=docsearch.as_retriever()
)


from langchain_community.document_loaders import WebBaseLoader
loader = WebBaseLoader("https://gtyan.com/archives/196")
docs = loader.load()
web_texts = text_splitter.split_documents(docs) 
web_db = Chroma.from_documents(
    web_texts, embeddings, 
    collection_name="UML-collection"
)
web_ret = RetrievalQA.from_chain_type(
    llm=llm, 
    chain_type="stuff", 
    retriever=web_db.as_retriever()
)


from langchain_core.prompts import PromptTemplate

template = """
SYSTEM
Assistant is a large language model trained by OpenAI.
Assistant is designed to be able to assist with a wide range of tasks, from answering simple questions to providing in-depth explanations and discussions on a wide range of topics. As a language model, Assistant is able to generate human-like text based on the input it receives, allowing it to engage in natural-sounding conversations and provide responses that are coherent and relevant to the topic at hand.
Assistant is constantly learning and improving, and its capabilities are constantly evolving. It is able to process and understand large amounts of text, and can use this knowledge to provide accurate and informative responses to a wide range of questions. Additionally, Assistant is able to generate its own text based on the input it receives, allowing it to engage in discussions and provide explanations and descriptions on a wide range of topics.
Overall, Assistant is a powerful system that can help with a wide range of tasks and provide valuable insights and information on a wide range of topics. Whether you need help with a specific question or just want to have a conversation about a particular topic, Assistant is here to assist.

PLACEHOLDER
chat_history

HUMAN
TOOLS
------
Assistant can ask the user to use tools to look up information that may be helpful in answering the users original question. The tools the human can use are:
{tools}
RESPONSE FORMAT INSTRUCTIONS
----------------------------
When responding to me, please output a response in one of two formats:
**Option 1:**
Use this if you want the human to use a tool.
Markdown code snippet formatted in the following schema:
```json
{{
    "action": string, \ The action to take. Must be one of {tool_names}
    "action_input": string \ The input to the action
}}
```
**Option #2:**
Use this if you want to respond directly to the human. Markdown code snippet formatted in the following schema:
```json
{{

    "action": "Final Answer",
    "action_input": string \ You should put what you want to return to use here
}}
```

USER'S INPUT
--------------------
Here is the user's input (remember to respond with a markdown code snippet of a json blob with a single action, and NOTHING else):
{input}

PLACEHOLDER
{agent_scratchpad}
"""

prompt = PromptTemplate.from_template(template)

from langchain.agents import AgentExecutor,  Tool, create_json_chat_agent

tools = [
    Tool(
        name="prompt skills",
        func=doc_ret.run,
        description="当你需要回答关于提示词的相关问题时，使用此工具。输入的问题应当完整。",
    ),
    Tool(
        name="UML collection",
        func=web_ret.run,
        description="当你需要回答关于UML中集合的相关问题时，使用此工具。输入的问题应当完整。",
    ),
]

agent = create_json_chat_agent(
    llm=llm, 
    tools=tools, 
    prompt=prompt
)
agent_executor = AgentExecutor(
    agent=agent, 
    tools=tools, 
    verbose=False, 
    handle_parsing_errors=False
)

question = "在与大语言模型交互时，如果使用带用歧义的提示词，大语言模型能否理解？"
print(f"\n问题1：{question}")
ae = agent_executor.invoke({"input": f"{question}"})
print(f"\n回答：{ae}")

question = "在UML中需要使用成员唯一但无序的集合时，应选择哪个集合？"
print(f"\n问题2：{question}")
ae = agent_executor.invoke({"input": f"{question}"})
print(f"\n回答：{ae}")